import axios from 'axios';

export interface VersionInfo {
    version: string;
    changelog?: string;
    forceUpdate?: boolean;
}

/**
 * 检查是否有新版本可用
 * @param currentVersion 当前版本号
 * @returns 版本信息
 */
export const checkForUpdates = async (currentVersion: string): Promise<VersionInfo | null> => {
    const maxRetries = 3;
    let retryCount = 0;

    while (retryCount < maxRetries) {
        try {
            // 获取服务器上的版本信息
            const response = await axios.get<VersionInfo>('/version.json', {
                // 添加时间戳防止缓存
                params: { t: new Date().getTime() },
                timeout: 5000, // 5秒超时
            });
            console.log('获取版本信息成功', response.data)
            const { version: latestVersion, changelog, forceUpdate } = response.data;

            // 比较版本号
            if (latestVersion !== currentVersion) {
                return {
                    version: latestVersion,
                    changelog,
                    forceUpdate,
                };
            }
            return null;
        } catch (error) {
            retryCount++;
            if (retryCount === maxRetries) {
                console.error('检查更新失败:', error);
                return null;
            }
            // 等待一段时间后重试
            await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
        }
    }
    return null;
};